package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.util.thread.CurrentLoggedInUserIDData;
import com.qk.entity.Log;
import com.qk.management.mapper.LogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-10-17 18:33
 */
@Slf4j
@Aspect
@Component
public class LogWithAspect {
    @Autowired
    private LogMapper logMapper;

    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt(){
    }

    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp){
        Object returnValue;
        try {
            long startTime = System.currentTimeMillis();
            returnValue = pjp.proceed();
            long endTime = System.currentTimeMillis();
            String className = pjp.getTarget().getClass().getName();
            String methodName = pjp.getSignature().getName();
            Object args = pjp.getArgs();
            String result = JSONUtil.toJsonStr(returnValue);
            String params = JSONUtil.toJsonStr(args);
            Log log = Log.builder()
                    .operateUserId(CurrentLoggedInUserIDData.get())
                    .operateTime(LocalDateTime.now())
                    .className( className)
                    .methodName(methodName)
                    .methodParams(params)
                    .returnValue(result)
                    .costTime((int)(endTime-startTime))
                    .build();
            logMapper.insert(log);
        }catch (Throwable e){
            returnValue = Result.error("操作失败");
            log.error("操作失败:{}",e.getMessage());
        }
        return returnValue;
    }
}
